//===============================================================================
// Q4Tech Engineering Team
// Mobile Updater Application Block - November 2006
//===============================================================================
// Copyright  Q4Tech Informatica Argentina.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using Q4Tech.Engineering.Ipc;

namespace Q4Tech.Engineering.UpdaterAgent.Common
{
    public class NotifierClient : IDisposable
    {
        string appName;

        public delegate bool UpdatingInProcessHandler();
        public event UpdatingInProcessHandler UpdatingInProcess;

        public delegate bool UpdatesAvailableHandler();
        public event UpdatesAvailableHandler UpdatesAvailable;

        private IpcCallServer<int, bool> updatesAvailableServer;


        public NotifierClient(string appName)
        {
            this.appName = appName.ToUpper();
        }

        public void Initialize()
        {
            string updatesAvailableName = String.Format("UpdaterService_UpdatesAvailable_{0}", appName);
            updatesAvailableServer = new IpcCallServer<int, bool>(PointToPointMessageQueueFactory.Instance, updatesAvailableName, new IpcCallServer<int, bool>.CallbackHandler(OnUpdatesAvailable));

        }

        public void Dispose()
        {
            if (updatesAvailableServer != null)
                updatesAvailableServer.Dispose();
        }

        private bool OnUpdatesAvailable(IpcCallMessage<int> data)
        {
            switch ((NotificationEventType)data.Data)
            {
                case NotificationEventType.UpdateAvailable:
                    {
                        if (UpdatesAvailable != null)
                            return UpdatesAvailable();
                    }
                    break;
                case NotificationEventType.UpdateInProcess:
                    {
                        if (UpdatingInProcess != null)
                            return UpdatingInProcess();
                    }
                    break;
                default:
                    break;
            }

            return true;
        }
    }
}
